package com.xl.cloud.netty.nio;

import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author XiangLiang
 * @Since 2025/1/9 13:37
 * @Description: NIOFileChannel02类 - 读出文件
 */
public class NIOFileChannel02 {
    public static void main(String[] args) throws Exception {
        // 创建文件输入流
        File file = new File("D:\\file01.txt");
        FileInputStream fileInputStream = new FileInputStream(file);

        // 通过FileInputStream获取FileChannel-> 实际类型为FileChannelImpl
        FileChannel fileChannel = fileInputStream.getChannel();

        // 创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());

        // 将通道中的数据读到Buffer
        fileChannel.read(byteBuffer);

        // 将Buffer中的数据转为字符串
        System.out.println(new String(byteBuffer.array()));

        // 关闭流和通道
        fileInputStream.close();
        fileChannel.close();
    }
}
